<template>
  <div class="add-btn">
    <el-dialog title="新增用户" :visible.sync="dialogVisible" :width="user.roleName === 'TENANT_ADMIN' ? '880px' : '480px'"
      :append-to-body="true" @close="closeAddDialog" :close-on-click-modal="false">
      <div class="divice-box" style="display: flex">
        <div class="box-1" style="width: 50%" :style="{
          width:
            user.roleName === 'TENANT_ADMIN' || user.roleName === 'ORG_ADMIN'
              ? '50%'
              : '100%',
        }">
          <el-form class="form-style" :model="addForm" :rules="rules" :inline="true" ref="refAddForm"
            label-width="100px">
            <el-form-item size="small" prop="mobile" label="手机号">
              <el-input clearable oninput="value=value.replace(/[^\d]/g,'')"
                @blur="addForm.mobile = $event.target.value" v-model="addForm.mobile" placeholder="请输入"
                maxlength="11" style="width: 300px"></el-input>
            </el-form-item>

            <el-form-item size="small" prop="username" label="用户名">
              <el-input clearable maxlength="18" v-model="addForm.username" placeholder="请输入"
                oninput="value=value.replace(/\s*/g,'')" @blur="addForm.username = $event.target.value"
                style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item size="small" prop="passWord" label="密码">
              <el-input clearable v-model="addForm.passWord" placeholder="请输入" show-password autocomplete="off"
                oninput="value=value.replace(/\s*/g,'')" maxlength="16" readOnly
                @input.native="onInput($event, addForm.passWord)" @mousedown.native="onMousedown"
                style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item size="small" prop="verifyPassWord" label="确认密码">
              <el-input clearable v-model="addForm.verifyPassWord" placeholder="请输入" show-password autocomplete="off"
                oninput="value=value.replace(/\s*/g,'')" maxlength="16" readOnly
                @input.native="onInput($event, addForm.verifyPassWord)" @mousedown.native="onMousedown"
                style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item size="small" prop="roleId" label="角色">
              <el-select v-model="addForm.roleId" placeholder="请选择" @change="roleChange" style="width: 300px">
                <el-option v-for="item in roleList" :key="item.id" :label="item.description" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item size="small" prop="orgRole" label="岗位" v-if="user.roleName === 'TENANT_ADMIN'">
              <el-select v-model="addForm.orgRole" placeholder="请选择" style="width: 300px">
                <el-option v-for="item in orgRoleList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="user.roleName === 'PLATFORM_ADMIN'" size="small" prop="enterpriseId" label="租户">
              <el-select v-model="addForm.enterpriseId" placeholder="请选择" filterable style="width: 300px">
                <el-option v-for="item in enterpriseList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="box-2" style="width: 50%" v-if="
          user.roleName === 'TENANT_ADMIN' || user.roleName === 'ORG_ADMIN'
        ">
          <div style="display: flex">
            <span class="ogText">组织机构</span>
            <el-tree v-if="isTree" :data="treeData" :props="defaultProps" show-checkbox node-key="id" ref="refTree"
              highlight-current @getCurrentNode="getCurrentNode" :load="loadNode" lazy
              style="padding-top: 0; height: 330px; width: 82%">
            </el-tree>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeAddDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" @click="addSubmit" v-preventReClick="1000" class="confirm-button">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { handleTree, transTree } from "@utils/trans-tree";
import { addUser, reqOrgList } from "@/api/api";
import { validateUsername, validatePass, validMobile } from "@utils/validate";
import { mapState } from "vuex";
import mixinPwd from "@utils/mixin/PreBrowserDefaultPassPop";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";

export default {
  name: "addUser",
  props: ["roleList", "enterpriseList"],
  mixins: [mixinPwd, tableStyleMixin],
  components: { treeselect, Pagination },
  data() {
    var checkPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.addForm.passWord) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.orgName,
          children: node.children,
        };
      },
      expandedKeys: false,
      page: 1,
      limit: 5,
      total: 0,
      // orgIdList:[],//组织机构id集
      isRadio: false,
      dialogVisible: false, //弹框是否显示
      // 新增用户信息数据
      addForm: {
        mobile: "",
        passWord: "",
        verifyPassWord: "",
        username: "",
        nickname: "",
        enterpriseId: "",
        roleId: "", // 角色id
        // orgId: null, //组织机构id
        orgIdList: [], //组织机构id集
        orgRole: "",
      },
      orgRoleList: [
        {
          id: 2,
          name: "消防安全专员",
        },
        {
          id: 3,
          name: "消防安全负责人",
        },
        {
          id: 4,
          name: "消防监管人",
        },
        {
          id: 5,
          name: "专职消防安全管理人",
        },
        {
          id: 6,
          name: "楼(建筑)长",
        },
        {
          id: 7,
          name: "维保人员",
        },
      ],
      projectList: [], //组织机构数据
      projectPage: 1,
      projectLimit: 10,
      projectTotal: 0,
      // 表单修改验证信息
      rules: {
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 位",
            trigger: "blur",
          },
        ],
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            validator: validateUsername,
          },
        ],
        passWord: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            validator: validatePass,
          },
        ],
        verifyPassWord: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            validator: checkPass,
          },
        ],
        imageCode: [
          {
            required: true,
            message: "请输入图形验证码",
            trigger: "blur",
          },
        ],
        smsCode: [
          {
            required: true,
            message: "请输入短信验证码",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: validMobile,
          },
        ],
        roleId: [
          {
            required: true,
            message: "请选择角色",
            trigger: ["blur", "change"],
          },
        ],
        orgRole: [
          {
            required: true,
            message: "请选择岗位",
            trigger: ["blur", "change"],
          },
        ],
        enterpriseId: [
          {
            required: true,
            message: "请选择租户",
            trigger: ["blur", "change"],
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
        ],
      },
      isThreeTeams: window.sessionStorage.getItem("threeTeams"),
      loadingSearch: false,
      orgName: "",
      defaultProps: {
        children: "children",
        label: "orgName",
        isLeaf: "hasChildren",
        id: "id",
      },
      treeData: [],
      // 选择的数据
      iconId: "",
      parentCheckedId: 0,
      typeId: 0,
      // 选择的数据
      parentIdList: [],
      isTree: true,
    };
  },
  computed: {
    ...mapState(["companyId", "user"]),
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.updateOrg();
      }
    },
  },
  methods: {
    // 树节点懒加载
    async loadNode(node, resolve) {
      if (node.level == 0) {
        // 如果是一级单位
        let params = {
          tenantId: this.user.tenantId,
          userId: this.user.userId,
          roleName: this.user.roleName,
          orgName: this.orgName,
        };
        let res = await reqOrgList(params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        let { rows, total } = res.data;
        rows.forEach((item) => {
          if (item.hasChildren === 1) {
            item.hasChildren = false;
          } else {
            item.hasChildren = true;
          }
        });
        this.treeData = rows;
        return resolve(rows);
      } else {
        // 否则是下级单位
        let params = {
          tenantId: this.user.tenantId,
          userId: this.user.userId,
          roleName: this.user.roleName,
          // orgName: this.orgName,
          orgName: "",
          parentId: node.data.id,
        };
        let res = await reqOrgList( params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        let rows = res.data.rows;
        rows.forEach((item) => {
          if (item.hasChildren === 1) {
            item.hasChildren = false;
          } else {
            item.hasChildren = true;
          }
        });
        return resolve(rows);
      }
    },
    // 更新整个单位
    updateOrg() {
      this.isTree = false;
      setTimeout(() => {
        this.isTree = true;
      }, 0);
    },
    // 查询组织机构
    async searchClick() {
      this.loadingSearch = true;
      await this.OrgList();
      this.loadingSearch = false;
    },
    // 单选（限制多选）
    selected(selection, row) {
      // console.log(selection, row);
      if (selection.length <= 0) this.addForm.orgIdList = []; //如果取消了勾选则清空数组
      if (this.addForm.roleId === "") {
        this.$refs.refTable.clearSelection();
        this.$modal.notifyWarning("请先选择角色");
        return;
      }
      // 组织机构只能单选
      if (this.isRadio) {
        if (selection.length === 1) {
          this.addForm.orgIdList = [row.id];
        } else if (selection.length > 1) {
          this.addForm.orgIdList = [];
          this.$refs.refTable.clearSelection();
          this.$refs.refTable.toggleRowSelection(selection.pop());
          // this.$nextTick(() => {
          this.addForm.orgIdList = [row.id];
          // });
        }
      }
    },
    getSimpleCheckedNodeIds(originData) {
      // 定义数组
      const checkedNodeIds = [];
      // 判断是否为全选，若为全选状态返回被选中的父节点数据，不为全选状态正常返回被选中的子节点的数据
      const isAllChecked = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes;
        childNodes.forEach((child) => {
          console.log(child, "child");
          if (child.checked) {
            checkedNodeIds.push(child.data);
          }
          if (child.indeterminate) {
            isAllChecked(child);
          }
        });
      };
      isAllChecked(originData);
      console.log(checkedNodeIds, "checkedNodeIds");
      return checkedNodeIds;
    },
    getCurrentNode(e) {
      console.log(e, "eee");
    },
    // 限制全选按钮
    selectAll() {
      if (this.addForm.roleId === "") {
        this.$refs.refTable.clearSelection();
        this.$modal.notifyWarning("请先选择角色");
        return;
      }
      // if (this.addForm.roleId == "3") {
      //   this.$refs.refTable.clearSelection();
      //   this.$modal.notifyWarning("组织机构管理员只能单选");
      //   return;
      // }
    },
    // select获取组织机构id  多选
    handleSelectionChange(val) {
      // console.log(val);
      if (this.isRadio) return; //如果是单选，则不走下面，以免搞乱
      this.addForm.orgIdList = [];
      let that = this;
      val.forEach((e) => {
        that.addForm.orgIdList.push(e.id);
      });
      this.addForm.orgIdList = [...new Set(this.addForm.orgIdList)];
    },
    // 角色选择：限制单选多选  如果是组织机构人员，则单选
    roleChange(val) {
      // console.log(val);
      if (val == "3") {
        // 组织机构管理员
        // this.$refs.refTable.clearSelection();
        // this.addForm.orgIdList = [];
        // this.isRadio = true;
        this.isRadio = false;
      } else {
        this.isRadio = false;
      }
    },
    // 点击获取图形验证码
    async reqVerification() {
      const res = await reqImageCode();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$nextTick(() => {
        this.imageCodeSrc = res.data.imageCode;
      });
    },
    // 点击获取手机验证码
    async getSmsCode() {
      let { mobile, imageCode } = this.addForm;
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!mobile) return this.$modal.notifyWarning("请先填写手机号");
      if (!reg.test(mobile))
        return this.$modal.notifyWarning("请输入正确的手机号");
      if (!imageCode) return this.$modal.notifyWarning("请先填写图形验证码");
      const res = await reqSmsCode({
        imageCode: this.addForm.imageCode,
        mobile: this.addForm.mobile,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifyWarning("请注意查收手机短信验证码");
      this.showCountDown = false;
      this.countDown = 60;
      this.isNext = false;
      let intervalId = setInterval(() => {
        if (this.countDown > 0 && this.countDown <= 60) {
          this.countDown--;
        } else {
          this.showCountDown = true;
          clearInterval(intervalId);
          intervalId = null;
        }
      }, 1000);
    },
    // 获取组织机构列表
    async OrgList() {
      this.projectList = [];
      var res = await reqOrgList({
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        orgName: this.orgName,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.projectList = res.data.rows;
      this.total = res.data.total;
      // let { rows } = res.data;
      // this.projectList = handleTree(rows);
      // let projectList = this.projectList;
      // projectList.forEach((item) => {
      //   if (item.hasChildren == 1) {
      //     item.children = null;
      //   }
      // });
      // this.projectList = projectList;
      // console.log(projectList);
    },
    // 新增按钮
    addSubmit() {
      this.$refs.refAddForm.validate(async (valid) => {
        if (!valid) return;
        // if (this.user.roleName === "PLATFORM_ADMIN") {
        //   this.$modal.notifyWarning(
        //     "请检查您的手机号、用户名、昵称输入或者角色、租户选择是否错误"
        //   );
        // } else {
        //   this.$modal.notifyWarning(
        //     "请检查您的手机号、用户名、昵称输入或者角色选择是否错误"
        //   );
        // }

        // 超级
        if (this.user.roleName === "SUPER_ADMIN") {
          const res = await addUser({
            userAddList: [
              {
                mobile: this.addForm.mobile,
                nickname: this.addForm.username,
                username: this.addForm.username,
                passWord: this.addForm.passWord,
                verifyPassWord: this.addForm.verifyPassWord,
                roleId: this.addForm.roleId,
                tenantId: "",
                orgIdList: [],
                orgRole: "",
              },
            ],
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("添加用户成功");
          this.$parent.userList(); //更新用户列表
          this.closeAddDialog();
        } else if (this.user.roleName === "PLATFORM_ADMIN") {
          // 运维
          const res = await addUser({
            userAddList: [
              {
                mobile: this.addForm.mobile,
                nickname: this.addForm.username,
                username: this.addForm.username,
                passWord: this.addForm.passWord,
                verifyPassWord: this.addForm.verifyPassWord,
                roleId: this.addForm.roleId,
                tenantId: this.addForm.enterpriseId,
                orgIdList: [],
                orgRole: "",
              },
            ],
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("添加用户成功");
          this.$parent.userList(); //更新用户列表
          this.closeAddDialog();
        } else {
          let orgList = this.getSimpleCheckedNodeIds(this.$refs.refTree.store);
          if (this.user.roleName === "TENANT_ADMIN") {
            if (orgList.length < 1)
              return this.$modal.notifyWarning("请选择一个组织机构"); //组织机构人员必须选择一个项目
          }
          let orgIdList = [];
          if (orgList.length) {
            orgIdList = Object.values(orgList.map((item) => item.id));
          }
          const res = await addUser({
            userAddList: [
              {
                mobile: this.addForm.mobile,
                nickname: this.addForm.username,
                username: this.addForm.username,
                passWord: this.addForm.passWord,
                verifyPassWord: this.addForm.verifyPassWord,
                roleId: this.addForm.roleId,
                tenantId: this.user.tenantId,
                orgIdList,
                orgRole: this.addForm.orgRole,
              },
            ],
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("添加用户成功");
          this.$parent.userList(); //更新用户列表
          this.closeAddDialog();
        }
      });
    },
    // 点击取消和关闭按钮 （ 清除验证  关闭弹窗）
    closeAddDialog() {
      if (this.user.roleName === "TENANT_ADMIN") {
        this.$refs.refTree.setCheckedKeys([]);
      }
      this.$refs.refAddForm.resetFields();
      this.dialogVisible = false;
    },
  },
  deactivated() {
    if (this.$refs.refTable != null || this.$refs.refAddForm != null) {
      this.closeAddDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("~@views/style/tablePage.less");
@import url("../../common.less");

.form-style {
  // display: flex;
  // flex-wrap: wrap;
  // justify-content: space-evenly;
  width: 100%;
}

/deep/ .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 26px;
}

// 分页器
::v-deep .el-pager {
  border-radius: 30px;
  background: @paginationBgcolor;
  margin: 0 5px;
  height: 32px;
}

::v-deep .el-pager li {
  min-width: 32px !important;
  background: @paginationBgcolor !important;
  color: #b4b7bd !important;
  height: 32px !important;
  line-height: 32px !important;
}

::v-deep .el-pager li.active {
  color: #fff !important;
  border-radius: 30px !important;
  background: #7367f0 !important;
}

::v-deep .el-pager li:first-child {
  border-radius: 30px !important;
}

::v-deep .el-pager li:last-child {
  border-radius: 30px !important;
}

::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background: #7367f0 !important;
}

::v-deep .el-tree {
  height: 100%;
  font-size: 14px;
  background: @primaryHeaderBgcolor;
  box-sizing: border-box;
  padding: 12px 10px;
  color: @primaryThemeTxtColor;
  overflow: hidden;
  overflow-y: scroll;
}

::v-deep .el-tree-node__content {

  // padding: 5px 0 !important;
  &:hover {
    background: @paginationBgcolor !important;
    border-radius: 4px;
  }
}

// ::v-deep .el-tree-node.is-current.is-focusable > .el-tree-node__content {
//   background-color: #7367f0 !important;
//   border-radius: 4px;
// }

::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
  padding: 5px 0;
}

// 解决点击白底问题
// ::v-deep .el-tree > .el-tree-node:first-of-type > .el-tree-node__content {
//   background-color: #7367f0 !important;
//   color: #f0f0f0;
// }

// 解决收起后白色背景问题
::v-deep .el-tree-node.is-expanded>.el-tree-node__content {
  background-color: transparent;
}

// 解决展开后白色背景问题
::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
  background-color: transparent;
  border-radius: 4px;
}

::v-deep .is-current>.el-tree-node__content>.el-tree-node__label {
  color: #f0f0f0;
}

.ogText {
  color: @primaryThemeTxtColor2;
}
</style>
